<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<!--				<el-form-item-->
				<!--					:label="$t('common.belong_merchant') + ':'"-->
				<!--					class="flex-row-container"-->
				<!--					label-width="77px"-->
				<!--				>-->
				<!--					<merchant-select-->
				<!--						v-model="queryData.merchantId"-->
				<!--						:merchantInfo.sync="merchantObj"-->
				<!--					></merchant-select>-->
				<!--				</el-form-item>-->
				<!-- <el-form-item>
						<el-select
							v-model="dateFlag"
							style="width:140px"
							:placeholder="$t('common.please_choose')"
						>
							<el-option
								:label="$t('report.dailyDimension')"
								value="1"
							/>
							<el-option
								:label="$t('report.monthDimension')"
								value="3"
							/>
							<el-option
								:label="$t('report.weekDimension')"
								value="2"
							/>
						</el-select>
					</el-form-item> -->
				<el-form-item label="返点结算周期:">
					<el-date-picker
						v-show="dateFlag === '1'"
						v-model="searchTime"
						type="daterange"
						:default-time="defaultTime"
						range-separator="-"
						:start-placeholder="$t('report.start_date')"
						:end-placeholder="$t('report.end_date')"
						:picker-options="pickerShortcutWithCurrPeriod"
						:clearable="false"
					></el-date-picker>
					<!-- <el-date-picker
							v-show="dateFlag === '2'"
							v-model="searchTime"
							type="daterange"
							:default-time="defaultTime"
							range-separator="-"
							:start-placeholder="$t('report.start_date')"
							:end-placeholder="$t('report.end_date')"
							:picker-options="pickerShortcut3"
							:clearable="false"
						></el-date-picker> -->
					<!-- <el-date-picker
							v-show="dateFlag === '3'"
							v-model="searchTime"
							type="monthrange"
							range-separator="-"
							:start-placeholder="$t('report.start_date')"
							:end-placeholder="$t('report.end_date')"
							:picker-options="pickerOptionsMonth"
							:clearable="false"
						></el-date-picker> -->
				</el-form-item>
				<el-form-item
					:label="$t('funds.fund_audit.rebate_state') + ':'"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.payoutStatus"
						size="medium"
						:placeholder="$t('common.select_all')"
						style="width: 200px"
						clearable
					>
						<el-option
							v-for="item in rebateArrList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>

				<!-- <el-form-item>
						<el-col :span="8">
							<el-select v-model="accountFlag">
								<el-option
									:label="$t('common.agent_number')"
									value="proxyName"
								/>
								<el-option
									:label="$t('report.general_account')"
									value="topProxyName"
								/>
							</el-select>
						</el-col>
						<el-col :span="16">
							<el-input
								v-if="accountFlag === 'proxyName'"
								v-model.trim="queryData.proxyName"
								clearable
								:placeholder="$t('common.please_enter')"
							></el-input>
							<el-input
								v-if="accountFlag === 'topProxyName'"
								v-model.trim="queryData.topProxyName"
								clearable
								:placeholder="$t('common.please_enter')"
							></el-input>
						</el-col>
					</el-form-item> -->
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('702081')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
					<el-button
						type="success"
						icon="el-icon-sort"
						:disabled="loading"
						size="medium"
						@click="openColSettings"
					>
						{{ $t('common.row_set') }}
					</el-button>
				</el-form-item>
				<date-picker-shortcuts
					kind="shortcutForButtons"
					:action="handleShortcutBtnClick"
					:loading="loading"
				/>
			</el-form>
			<el-link :underline="false" type="danger">
				{{ $t('report.refresh_warning_text') }}
			</el-link>
		</template>
		<template slot="content">
			<el-table
				key="father"
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				:max-height="tableHeight"
				show-summary
				:summary-method="
					(val) => handleRow(val, subSummary, totalSummary)
				"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					prop="cycleStartDate"
					align="center"
					:label="$t('report.rebate_cycle')"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.cycleStartDate || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[$t('funds.fund_audit.rebate_state')]"
					key="payoutStatus"
					prop="payoutStatus"
					align="center"
					:label="$t('funds.fund_audit.rebate_state')"
					show-overflow-tooltip
					min-width="200"
				>
					<template slot-scope="scope">
						<span v-if="scope.row.payoutStatusList.length > 0">
							<span>
								{{
									typeListFilter(
										scope.row.payoutStatusList,
										'rebateArrList'
									) || '-'
								}}
							</span>
						</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[$t('report.rebates_number')]"
					prop="rebateNumber"
					align="center"
					:label="$t('report.rebates_number')"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-link
							class="lightBlueColor"
							type="primary"
							@click="dialogData(scope.row)"
						>
							{{ handleNumber('', scope.row.rebateNumber, 0) }}
						</el-link>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[$t('report.actual_rebate')]"
					prop="distributeOfRebate"
					align="center"
					min-width="200"
					width="130"
					:label="$t('report.actual_rebate')"
					show-overflow-tooltip
				>
					<template slot="header">
						{{ $t('report.actual_rebate') }}
						<!-- <el-tooltip class="tips-box" effect="dark">
								<i class="el-icon-warning"></i>
								<div slot="content">
									{{ $t('report.actual_rebate_describle') }}
								</div>
							</el-tooltip> -->
					</template>
					<template slot-scope="scope">
						<p>
							{{
								handleTotalNumber(
									'USDT',
									scope.row.distributeOfRebate
								)
							}}
						</p>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[$t('report.rebate_distribution')]"
					prop="personRebateAmount"
					align="center"
					:label="$t('report.rebate_distribution')"
					show-overflow-tooltip
					min-width="200"
				>
					<template slot-scope="scope">
						<p>
							{{
								handleTotalNumber(
									'USDT',
									scope.row.personRebateAmount
								)
							}}
						</p>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[$t('report.rebate_adjustment')]"
					key="adjustOfRebate"
					prop="adjustOfRebate"
					align="center"
					:label="$t('report.rebate_adjustment')"
					show-overflow-tooltip
					min-width="200"
				>
					<template slot-scope="scope">
						<p :style="handleNumberColor(scope.row.adjustOfRebate)">
							{{
								handleTotalNumber(
									'USDT',
									scope.row.adjustOfRebate
								)
							}}
						</p>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<detail-page
			v-if="showDialog"
			:rowVal="rowVal"
			:closeDialog="
				(val) => {
					showDialog = val
				}
			"
		/>
		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			class="setting-div"
		>
			<div>
				<el-link type="primary" class="mb15" @click="clickDel">
					复原缺省
				</el-link>
			</div>
			<div
				v-for="(value, name1) in activityListField"
				:key="name1"
				class="setting-div"
			>
				<el-checkbox v-model="dialogColumnData[name1]">
					{{ name1 }}
				</el-checkbox>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="colSettings.visible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import summaryList from './components/summaryList'
import MainContent from '@/components/MainContent/index.vue'
import DatePickerShortcuts from '@/components/DatePickerShortcuts'
export default {
	name: routerNames.rebatePeriodReport,
	components: {
		DetailPage: () => import('./components/detail-page.vue'),
		MainContent,
		DatePickerShortcuts
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			dateFlag: '1',
			queryData: {
				payoutStatus: undefined,
				merchantId: ''
			},
			searchTime: [],
			// accountFlag: 'proxyName',
			tableData: [],
			subSummary: {},
			totalSummary: {},
			exportBtnLoading: false,
			merchantObj: '',
			axiosDate: '',
			showDialog: false,
			loading: false,
			colSettings: {
				visible: false,
				dialogColumnData: {}
			},
			activityListField: {
				// 返点人数: true,
				// 实际返点: true,
				// 返点发放: true,
				// 返点调整: true,
				[this.$t('funds.fund_audit.rebate_state')]: true,
				[this.$t('report.rebates_number')]: true,
				[this.$t('report.actual_rebate')]: true,
				[this.$t('report.rebate_distribution')]: true,
				[this.$t('report.rebate_adjustment')]: true
			}
		}
	},
	computed: {
		rebateArrList() {
			return this.globalDics.rebateArrList || []
		}
	},
	watch: {
		// accountFlag: {
		// 	handler(newVal, oldVal) {
		// 		this.$set(this.queryData, newVal, '')
		// 		this.$set(this.queryData, oldVal, '')
		// 	},
		// 	immediate: true
		// }
		dateFlag: {
			handler(newVal, oldVal) {
				if (newVal === '1') {
					const start = dayjs()
						.startOf('day')
						.subtract(7, 'd')
					const end = dayjs()
						.endOf('day')
						.subtract(1, 'd')
					this.searchTime = [start, end]
				} else if (newVal === '2') {
					const end = dayjs()
						.subtract(1, 'week')
						.endOf('week')
						.subtract(-1, 'day')
					const start = dayjs()
						.startOf('week')
						.subtract(7, 'week')
						.subtract(-1, 'day')
					this.searchTime = [start, end]
				} else if (this.dateFlag === '3') {
					const end = dayjs()
						.subtract(1, 'month')
						.endOf('month')
					const start = dayjs()
						.startOf('month')
						.subtract(7, 'month')
					this.searchTime = [start, end]
				}
			},
			immediate: true
		}
	},
	created() {
		this.$store.dispatch('user/updateCurrentAccountPeriod')
		this.initIndexDB('rebatePeriodReport', this.activityListField)
	},
	mounted() {},
	methods: {
		handleShortcutBtnClick(val) {
			this.searchTime = val
			this.loadData()
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			this.updateIndexDB()
		},
		// 打开列设置弹框
		openColSettings() {
			this.getIndexDB(this.activityListField)
			this.colSettings.visible = true
		},
		clickDel() {
			this.dialogColumnData = {}
			this.dialogColumnData = {
				// 返点人数: true,
				// 实际返点: true,
				// 返点发放: true,
				// 返点调整: true,
				[this.$t('funds.fund_audit.rebate_state')]: true,
				[this.$t('report.rebates_number')]: true,
				[this.$t('report.actual_rebate')]: true,
				[this.$t('report.rebate_distribution')]: true,
				[this.$t('report.rebate_adjustment')]: true
			}
		},
		dialogData(val) {
			this.rowVal = {
				merchantId: val.merchantId,
				cycleType: this.dateFlag,
				currency: val.currency,
				playerId: val.playerId,
				parentProxyId: val.parentProxyId,
				userName: val.userName,
				startDate: val.cycleStartDate,
				endDate: val.cycleEndDate,
				payoutStatus: this.queryData.payoutStatus
			}
			this.showDialog = true
		},
		loadData() {
			if (+new Date() - 500 < this.axiosDate) return
			const timeArr = this.searchTime || []
			// if (!this.$store.getters.isZk) {
			// 	this.queryData.merchantId = this.$store.getters.merchantInfo.id
			// }
			// else {
			// 	this.queryData.merchantId = this.queryData.merchantId
			// 		? this.queryData.merchantId
			// 		: this.$store.getters.merchantList[0].id
			// }
			const params = {
				cycleType: this.dateFlag,
				...this.queryData,
				startDate:
					this.dateFlag === '3'
						? dayjs(timeArr[0]).format('YYYYMM')
						: dayjs(timeArr[0]).format('YYYYMMDD'),
				endDate:
					this.dateFlag === '3'
						? dayjs(timeArr[1]).format('YYYYMM')
						: dayjs(timeArr[1]).format('YYYYMMDD'),
				...this.getParams()
			}
			// if (this.dateFlag === '1') {
				// const min = dayjs(timeArr[0])
				// const max = dayjs(timeArr[1])
				// const day = dayjs(max).diff(min, 'day')
				// if (day >= 31) {
				// 	this.$message.warning(this.$t('report.31_day'))
				// 	this.total = 0
				// 	return
				// }
			// } else if (this.dateFlag === '2') {
				// const minWeek = dayjs(timeArr[0])
				// const maxWeek = dayjs(timeArr[1])
				// const weeks = dayjs(maxWeek).diff(minWeek, 'day')
				// if (weeks >= 92) {
				// 	this.$message.warning(this.$t('report.92_day'))
				// 	this.total = 0
				// 	return
				// }
			// } else if (this.dateFlag === '3') {
			// 	const minMonth = dayjs(timeArr[0])
			// 	const maxMonth = dayjs(timeArr[1])
			// 	const months = dayjs(maxMonth).diff(minMonth, 'month')
			// 	if (months >= 12) {
			// 		this.$message.warning(this.$t('report.12_months'))
			// 		this.total = 0
			// 		return
			// 	}
			// }

			this.loading = true
			this.pageCurrency = this.merchantObj?.currency || ''
			this.$api
				.getReportPreviousRebateList(params)
				.then((res) => {
					this.loading = false
					this.axiosDate = +new Date()
					if (res.code === 200) {
						this.tableData = []
						this.tableData = res?.data?.record || []
						this.total = res?.data?.totalRecord || 0
						this.subSummary = res?.data?.summary || {}
					}
				})
				.catch(() => {
					this.loading = false
				})
			this.$api
				.getReportPreviousRebateSummary(params)
				.then((res) => {
					this.loading = false
					if (res.code === 200) {
						this.totalSummary = res?.data || {}
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.pageNum = 1
			this.queryData = {
				merchantId: this.$store.getters.merchantList[0].id
			}
			this.dateFlag = '1'
			this.merchantObj = ''
			if (this.dateFlag === '1') {
				const start = dayjs()
					.startOf('day')
					.subtract(7, 'd')
				const end = dayjs()
					.endOf('day')
					.subtract(1, 'd')
				this.searchTime = [start, end]
			} else if (this.dateFlag === '2') {
				const end = dayjs()
					.subtract(1, 'week')
					.endOf('week')
					.subtract(-1, 'day')
				const start = dayjs()
					.startOf('week')
					.subtract(7, 'week')
					.subtract(-1, 'day')
				this.searchTime = [start, end]
			} else if (this.dateFlag === '3') {
				const end = dayjs()
					.subtract(1, 'month')
					.endOf('month')
				const start = dayjs()
					.startOf('month')
					.subtract(7, 'month')
				this.searchTime = [start, end]
			}
			this.loadData()
		},
		handleExportExcel() {
			const timeArr = this.searchTime || []
			const params = {
				cycleType: this.dateFlag,
				...this.queryData,
				startDate:
					this.dateFlag === '3'
						? dayjs(timeArr[0]).format('YYYYMM')
						: dayjs(timeArr[0]).format('YYYYMMDD'),
				endDate:
					this.dateFlag === '3'
						? dayjs(timeArr[1]).format('YYYYMM')
						: dayjs(timeArr[1]).format('YYYYMMDD')
			}
			// const min = dayjs(timeArr[0])
			// const max = dayjs(timeArr[1])
			// const day = dayjs(max).diff(min, 'day')
			// if (day >= 31) {
			// 	this.$message.warning(this.$t('report.31_day'))
			// 	return
			// }
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'getReportPreviousRebateExport',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
	font-size: 24px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
</style>
